package hrms.controller;

import com.alibaba.fastjson.JSONObject;
import hrms.annotation.UserLoginToken;
import hrms.entity.Account;
import hrms.entity.Result;
import hrms.service.AccountService;
import hrms.util.JWTUtil;
import hrms.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping
public class LoginController {
    @Autowired
    AccountService accountService;
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody Account account){
        Account accountForBase=accountService.findByPhone(account);
        if(accountForBase==null){
            return Result.fail().error("登录失败,用户不存在");
        }else {
            if (!accountForBase.getPassword().equals(MD5Util.getMd5(account.getPassword()))){
                return Result.fail().error("登录失败,密码错误");
            }else {
                String token = JWTUtil.sign(accountForBase);
                Map<String,Object> map = new HashMap<>();
                map.put("token", token);
                map.put("account", accountForBase);
                map.put("message","登录成功");
                return Result.success().addMap(map);
            }
        }
    }

    @PostMapping("/signup")
    public Result signup(@RequestBody Account account){
        Account account1 = accountService.findByPhone(account);
        if(account1 != null){
            return Result.fail().error("注册失败，该手机号已被注册");
        }else {
            account.setPassword(MD5Util.getMd5(account.getPassword()));
            account.setPortrait("");
            account.setRole("");
            account.setUserId(-1);
            accountService.addAccount(account);
            return Result.success();
        }
    }



    @UserLoginToken
    @GetMapping("/getMessage")
    public JSONObject getMessage(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "你已通过验证");
        return jsonObject;
    }


}
